# ImageThumbnailer - Generates thumbnails from image files
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"
__maintainer__ = "Paul Hummer <paul@ironlionsoftware.no.spam.com>"

import os
import md5
import Image
from thumbnailer import Thumbnailer

class ImageThumbnailer(Thumbnailer):
    """ Thumbnailer for image files. """
    
    # Thumbnail directory
    THUMB_DIR = os.path.expanduser("~/.entertainer/cache/thumbnails/image")
    
    def __init__(self, filename):
        """Create a new Image thumbnailer"""
        self.filename = filename
    
    def create_thumbnail(self):
        """
        Method creates a new thumbnail and saves it to the Entertainer's
        thumbnail directory in PNG format. Thumbnail filename is a MD5
        hash of the given filename.
        """
        try:
            im = Image.open(self.filename)
        except:
            return # We can't generate thumbnail.
        
        # Create absolute path + filename for thumbnail
        m = md5.new()
        m.update(self.filename)
        new_filename = m.hexdigest() + ".jpg"
        thumb_file = os.path.join(self.__class__.THUMB_DIR, new_filename)

        # Calculate new size here
        original_width = im.size[0]
        original_height = im.size[1]
        if original_width <= self.MAX_WIDTH and original_height <= self.MAX_HEIGHT:
            try:
                im.save(thumb_file, "JPEG", quality=self.THUMB_QUALITY)
                return m.hexdigest()
            except:
                return ""
        else: 
            if original_width > original_height:
                width = self.MAX_WIDTH
                height = (width * original_height) / original_width
            else:
                height = self.MAX_HEIGHT
                width = (height * original_width) / original_height
            try:
                im.thumbnail((width, height), Image.ANTIALIAS)
                im.save(thumb_file, "JPEG", quality = self.THUMB_QUALITY)
                return m.hexdigest()
            except:
                return ""

